package com.ideaaedi.springcloud.jd.user.config.ext;

import com.ideaaedi.springcloud.jd.commonds.enums.user.LoginSceneEnum;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysRolePO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysUserPO;
import com.ideaaedi.springcloud.jd.commonspring.provider.UserIdTenantDataScopeProvider;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息模型
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.2.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class JdUserDetails extends SysUserPO implements UserDetails, UserIdTenantDataScopeProvider {
    
    /** 角色 */
    private List<SysRolePO> roles;
    
    /** 登录场景 */
    private LoginSceneEnum loginScene;
    
    /**
     * 数据范围去重叠后的可读数据范围的deptId对应的deptPath
     */
    private LinkedHashSet<String> distinctReadDataScopePaths;
    
    /**
     * 数据范围去重叠后的可写(修改/删除)数据范围的deptId对应的deptPath
     */
    private LinkedHashSet<String> distinctUpdateDataScopePaths;
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles == null ? Collections.emptySet() :
                roles.stream().map(SysRolePO::getId).map(String::valueOf).filter(StringUtils::isNotBlank)
                        .map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
    }
    
    @Override
    public String getPassword() {
        return super.getPassword();
    }
    
    @Override
    public String getUsername() {
        return this.getAccountNo();
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return this.getState() != null && this.getState() == 1;
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return this.getState() != null && this.getState() == 1;
    }
    
    @Override
    public Long obtainUserId() {
        return this.getId();
    }
    
    @Override
    public String obtainTenant() {
        return this.getTenant();
    }
    
    @Override
    public LinkedHashSet<String> distinctReadDataScopePaths() {
        return this.distinctReadDataScopePaths;
    }
    
    @Override
    public LinkedHashSet<String> distinctUpdateDataScopePaths() {
        return this.distinctUpdateDataScopePaths;
    }
}
